﻿using FDStudio.Core.Config;
using FDStudio.Core.Entities.Enums;
using FDStudio.Core.Exceptions;
using FDStudio.Core.Extensions;
using FDStudio.Core.Runtime;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;

namespace FDStudio.Core.Utils
{
    /*
    CreatedOn: 2018-03-07
    CreatedBy: Jackie Lee(天宇遊龍)
    */
    /// <summary>
    /// 数据连接查询帮助
    /// </summary>
    public class DbConnHelper
    {
        /// <summary>
        /// 切换数据库
        /// </summary>
        /// <param name="databaseType"></param>
        /// <param name="name"></param>
        public static IDbConnectionString GetConnectionConfig(DatabaseType databaseType, DatabaseOperType databaseOperType, string name = "")
        {
            var connConfigs = RuntimeContext.Current.Container.ResoveAll<IDbConnectionString>();
            if (connConfigs == null || connConfigs.Count() == 0)
                throw new DbConnectionConfigException("当前上下文中不存在数据库连接类型");
            var config = connConfigs.FirstOrDefault(c => c.DatabaseType == databaseType &&
                c.DatabaseOperType == databaseOperType &&
                c.IsEnable
                && (name.IsNullOrEmpty() ? true : c.Name == name));
            if (config == null)
            {
                // 说明未读写分离
                config = connConfigs.FirstOrDefault(c => c.DatabaseType == databaseType &&
                c.IsEnable &&
                c.DatabaseOperType == DatabaseOperType.ReadWrite
                && (name.IsNullOrEmpty() ? true : c.Name == name));
                if (config == null)
                    throw new DbConnectionConfigException($"当前上下文中不存在{databaseType}类型{databaseOperType}数据库连接类型");
            }
            return config;
        }
    }
}
